/*
 * @Description: 条件筛选基础组件
 * @Author: tangwenting
 */
import styles from './conditionSearch.module.scss';
import React, { useState } from 'react';
import { Button, Select, Form, Icon, Input, message, DatePicker } from 'antd';
import cx from 'classnames';
import PropTypes from 'prop-types';
import { isObject } from 'utils/util';
import cloneDeep from 'lodash/cloneDeep';
import { useEffect } from 'react';

const { Option } = Select;
const { RangePicker } = DatePicker;

function ConditionSearch({
    searchData,
    selfSearchData,
    form,
    searchBtn,
    title,
    extra,
    className,
    style,
    onSearch,
    getSearchOptions,
    resetAllConditions
}) {
    const { getFieldDecorator, setFieldsValue } = form;
    const copySearchData = cloneDeep(searchData);
    const [condition, setCondition] = useState(selfSearchData || copySearchData);
    const [showValueOptions, setShowValueOptions] = useState(false);

    useEffect(() => {
        resetAllConditions && setCondition(searchData);
        let temp = searchData.reduce((total, currentValue) => {
            total[currentValue.field] = currentValue.initialValue || currentValue.selected;
            return total;
        }, {});
        console.log(temp)
        setFieldsValue(temp)
    }, [searchData]);

    // 设置选中某项
    const setItemActive = (conditionItem, conditionIndex, value, disabled) => {
        const { mode, valueOptions } = conditionItem;
        if (disabled) {
            return;
        }
        const KEY = 'selected';
        const ALL = '不限';
        const newCondition = [...condition];
        if (mode === 'multiple') {
            let selectedValue = newCondition[conditionIndex][KEY];
            let vIndex = selectedValue.findIndex(v => v === value);
            if (vIndex > -1 && value !== ALL) { // 之前存在
                selectedValue.splice(vIndex, 1); // 删除
                if (selectedValue.length === 0) {
                    newCondition[conditionIndex][KEY] = [ALL]; // 当删除为空时候，均将值设置为不限
                }
            } else if (value === ALL) { // 当选择值为不限的时候，均将值设置为不限
                newCondition[conditionIndex][KEY] = [ALL];
            } else {
                if (selectedValue.includes(ALL)) {
                    selectedValue.splice(0, 1);
                } // 添加value存在不限，删除不限
                selectedValue.push(value); // 添加
            }
        } else if (value === newCondition[conditionIndex]['selectBy'] || (Array.isArray(newCondition[conditionIndex]['selectBy']) && newCondition[conditionIndex]['selectBy'].includes(value))) {
            newCondition[conditionIndex][KEY] = value;
            setShowValueOptions(true);
        } else if (newCondition[conditionIndex]['selected'] !== value || valueOptions.includes(newCondition[conditionIndex]['selectedOption'])) {
            newCondition[conditionIndex][KEY] = value;
            newCondition[conditionIndex]['selectedOption'] = ['北京'];
            setShowValueOptions(false);
            setOptionsExpand(false);
        }
        else {
            newCondition[conditionIndex][KEY] = value;
        }
        setCondition(newCondition);
        form.validateFields((err, values) => {
            if (!err) {
                let params = {};
                newCondition.forEach(item => {
                    let { field, selected } = item;
                    if (values.hasOwnProperty(field)) {
                        params['industry'] = values[field];
                    } else {
                        params[field] = selected;
                    }
                });
                getSearchOptions && getSearchOptions(params, newCondition);
            }
        });
    };

    // 展开搜索
    const setExpand = (conditionIndex, expand) => {
        const newCondition = [...condition];
        newCondition[conditionIndex]['expand'] = expand;
        setCondition(newCondition);
    };

    // 重置
    const onReset = () => {
        resetAllConditions && resetAllConditions();
        setCondition(copySearchData);
        setShowValueOptions(false);
        setOptionsExpand(false);
        form.resetFields();
    };

    // 直接查询
    const onSubmit = () => {
        form.validateFields((err, values) => {
            if (!err) {
                let params = {};
                condition.forEach(item => {
                    let { field, selected } = item;
                    if (values.hasOwnProperty(field)) {
                        params[field] = values[field];
                    } else {
                        params[field] = selected;
                    }
                });
                onSearch && onSearch(params);
                getSearchOptions && getSearchOptions(params, condition);
            }
        });
    };

    const setItemOptionActive = (conditionIndex, item) => {
        const KEY = 'selectedOption';
        const DEFAULT = '北京';
        const newCondition = [...condition];
        let selectedValue = newCondition[conditionIndex][KEY];
        let vIndex = selectedValue.findIndex(v => v === item);
        if (vIndex > -1 && selectedValue.length >= 1) {
            selectedValue.splice(vIndex, 1);
            if (selectedValue.length === 0) {
                message.warning('至少选择一项');
                newCondition[conditionIndex][KEY] = [DEFAULT];
            }
        }
        else {
            selectedValue.push(item);
        }
        setCondition(newCondition);
    };

    const [optionsExpand, setOptionsExpand] = useState(false);
    const renderValueOptions = (conditionItem, conditionIndex, options) => {
        const { maxOptionNumber, selectBy } = conditionItem;
        let conditionValue = [...options];
        if (maxOptionNumber && !optionsExpand) {
            conditionValue = conditionValue.slice(0, maxOptionNumber);
        }
        return (
            <dl className={styles.item} key={selectBy} style={{ marginBottom: 0 }}>
                {
                    options.length > maxOptionNumber ? <dd className={styles.expand} onClick={() => setOptionsExpand(!optionsExpand)}>{optionsExpand ? '收起' : '展开'}{optionsExpand ? <Icon type="up" /> : <Icon type="down" />} </dd> : null
                }
                <dd className={styles.content}>
                    <ul>
                        {conditionValue.map(item => {
                            return (
                                <li key={item}
                                    onClick={() => setItemOptionActive(conditionIndex, item)}
                                    className={cx({ [styles.active]: conditionItem.selectedOption.includes(item) })}>
                                    {item}
                                </li>
                            );
                        })}
                    </ul>
                </dd>
            </dl>
        );
    };

    const _renderItem = (conditionItem, conditionIndex, item, index) => {
        let name = item, disabled = false;
        if (isObject(item)) {
            name = item.name;
            disabled = item.disabled;
        }
        return <li key={name}
            onClick={() => setItemActive(conditionItem, conditionIndex, name, disabled)}
            className={cx({
                [styles.active]: conditionItem.mode === 'multiple' ? conditionItem.selected.includes(name) : conditionItem.selected === name,
                [styles.disabled]: disabled
            })}>
            {name}
        </li>;
    };

    const _renderConditionContent = (conditionItem, conditionIndex) => {
        let {
            value: conditionValue,
            expand,
            maxNumber,
            type,
            width = 300,
            placeholder,
            field,
            value,
            mode,
            selected,
            initialValue
        } = conditionItem;

        if (maxNumber && !expand) {
            conditionValue = conditionValue.slice(0, maxNumber);
        }
        switch (type) {
            case 'input':
                return getFieldDecorator(`${field}`)(<Input style={{ width }} placeholder={placeholder || '请输入关键词'} />);
            case 'datePicker':
                return getFieldDecorator(`${field}`)(<RangePicker style={{ width }} />);
            // 新增select 
            case 'select':
                // mode={mode || false} size={'small'} // 多选时, 选择框样式就崩了???
                return getFieldDecorator(`${field}`, { initialValue })(<Select style={{ width: width }} placeholder={placeholder || '请选择'}>
                    {
                        value.map(item => <Select.Option value={item} key={item}>{item}</Select.Option>)
                    }
                </Select>);
            default:
                return (
                    <ul>
                        {conditionValue.map((item, index) => {
                            return _renderItem(conditionItem, conditionIndex, item, index);
                        })}
                    </ul>
                );
        }
    };

    return (
        <div className={cx(styles.conditionSearch, className)} style={style}>
            {title ? <div className={styles.head}>
                <h3 className={styles.title}>{title}</h3>
                <span className={styles.extra}>{extra}</span>
            </div> : null}
            <Form >
                {
                    condition.map((conditionItem, conditionIndex) => {
                        let { value, type, expand, maxNumber, name: conditionName, valueOptions } = conditionItem;

                        return <dl className={styles.item} key={conditionName}>
                            <dt className={styles.conditionName}>{conditionName}：</dt>
                            {
                                !type && (value.length > maxNumber) ? <dd className={styles.expand} onClick={() => {
                                    setExpand(conditionIndex, !expand);
                                }}>{expand ? '收起' : '展开'}{expand ? <Icon type="up" /> : <Icon type="down" />} </dd> : null
                            }
                            <dd className={styles.content}>
                                {/* 每项条件内容 */}
                                {_renderConditionContent(conditionItem, conditionIndex)}
                                {showValueOptions && valueOptions && valueOptions.length > 0 && renderValueOptions(conditionItem, conditionIndex, valueOptions)}
                            </dd>
                        </dl>;
                    })
                }
                <div className={styles.footer}>
                    <Button size="large" onClick={onReset}>重置</Button>
                    {
                        searchBtn && <Button type="primary" size="large" onClick={onSubmit}>查询</Button>
                    }
                </div>
            </Form>
        </div>
    );
}

export default Form.create({
    onValuesChange: (props, changedValues, allValues) => {
        console.log('formValue 变化', props, changedValues, allValues)
    }
})(ConditionSearch);
ConditionSearch.defaultProps = {
    searchData: [],
    searchBtn: true
};

ConditionSearch.propTypes = {
    searchData: PropTypes.array,
    searchBtn: PropTypes.bool,
    form: PropTypes.object,
    title: PropTypes.string,
    extra: PropTypes.any,
    className: PropTypes.any,
    style: PropTypes.object,
    onSearch: PropTypes.func,
    getSearchOptions: PropTypes.func,
    resetAllConditions: PropTypes.func
};